import { Toast } from 'vant'

export default function ({ $axios,app:{route}, $cookies, redirect, store }) {
  $axios.onRequest((config) => {
    const token = config.headers.forceToken || $cookies.get('access_token')
    if (token) {
      config.headers.Authorization = token
    }
  })

  $axios.onResponse((response) => {
    // access_token过期
    if (response.data.code == 403) {
      console.log('token失效')
      const refresh_token = $cookies.get('refresh_token')
      return $axios.post('/v1/common/refreshToken', { refresh_token }).then((res) => {
        if (res.data.code == 200) {
          // 服务端设置cookie 未知原因失败 ，所以在客户端设置 一定要等请求结束才设置cookie...........
          $cookies.set('access_token', res.data.result.token, {
            maxAge: 60 * 60 * 24 * 30 * 1000,
            httpOnly: false,
            sameSite: true,
            signed: true,
            overwrite: true
          })
          $cookies.set('refresh_token', res.data.result.refreshToken, {
            maxAge: 60 * 60 * 24 * 30 * 1000,
            httpOnly: false,
            sameSite: true,
            signed: true,
            overwrite: true
          })
          response.config.headers.forceToken = res.data.result.token
          return $axios(response.config)
        }
      })
    }
    if (response.data.code != 200) {
      Toast.fail(response.data.msg)
    }
    // refresh_token过期
    if (response.data.code == 401) {
      $cookies.removeAll()
      store.commit('setLogin', false)
      redirect('/login?url='+route.path)
    }
    // token 不合法
    if (response.data.code == 400) {
      $cookies.removeAll()
      store.commit('setLogin', false)
      redirect('/login')
    }
    return Promise.resolve(response)
  })
}
